from django.core.management.base import BaseCommand
from django.contrib.auth.models import Permission as DjangoPermission
from apps.permissions.models import PermissionExtension


class Command(BaseCommand):
    help = '同步权限扩展 - 为所有Django权限创建对应的权限扩展'

    def handle(self, *args, **options):
        self.stdout.write('开始同步权限扩展...')
        
        # 获取所有Django权限
        all_permissions = DjangoPermission.objects.all()
        self.stdout.write(f'找到 {all_permissions.count()} 个Django权限')
        
        # 获取已存在的权限扩展
        existing_extensions = PermissionExtension.objects.values_list('permission_id', flat=True)
        self.stdout.write(f'已存在 {len(existing_extensions)} 个权限扩展')
        
        created_count = 0
        updated_count = 0
        
        for perm in all_permissions:
            # 检查是否已存在权限扩展
            extension, created = PermissionExtension.objects.get_or_create(
                permission=perm,
                defaults={
                    'module': perm.content_type.app_label,
                    'resource_path': f'/{perm.content_type.app_label}/{perm.content_type.model}/',
                    'api_endpoint': f'/api/{perm.content_type.app_label}/{perm.content_type.model}/',
                    'description': perm.name,
                    'status': 'active'
                }
            )
            
            if created:
                created_count += 1
                self.stdout.write(f'创建权限扩展: {perm.content_type.app_label}.{perm.codename}')
            else:
                # 更新现有权限扩展的状态为active
                if extension.status != 'active':
                    extension.status = 'active'
                    extension.save()
                    updated_count += 1
                    self.stdout.write(f'更新权限扩展状态: {perm.content_type.app_label}.{perm.codename}')
        
        self.stdout.write(
            self.style.SUCCESS(
                f'同步完成！创建了 {created_count} 个新权限扩展，更新了 {updated_count} 个权限扩展状态'
            )
        )
